const express = require('express');
const router = express.Router();
const { Op, Sequelize } = require('sequelize');
const { User, Order, Product, PointsTransaction, AdView } = require('../models');
const auth = require('../middleware/auth');
const adminAuth = require('../middleware/adminAuth');
const userAdminAuth = require('../middleware/userAdminAuth');

// 概览数据接口
router.get('/overview', auth, userAdminAuth, async (req, res) => {
  try {
    const { period = 'week' } = req.query;
    
    // 计算时间范围
    const now = new Date();
    let startDate, endDate, prevStartDate, prevEndDate;
    
    switch (period) {
      case 'day':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        endDate = new Date(startDate);
        endDate.setDate(endDate.getDate() + 1);
        prevStartDate = new Date(startDate);
        prevStartDate.setDate(prevStartDate.getDate() - 1);
        prevEndDate = new Date(startDate);
        break;
      case 'week':
        const dayOfWeek = now.getDay();
        startDate = new Date(now);
        startDate.setDate(now.getDate() - dayOfWeek);
        startDate.setHours(0, 0, 0, 0);
        endDate = new Date(startDate);
        endDate.setDate(endDate.getDate() + 7);
        prevStartDate = new Date(startDate);
        prevStartDate.setDate(prevStartDate.getDate() - 7);
        prevEndDate = new Date(startDate);
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
        prevStartDate = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        prevEndDate = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      default:
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 7);
        endDate = new Date(now);
        prevStartDate = new Date(startDate);
        prevStartDate.setDate(prevStartDate.getDate() - 7);
        prevEndDate = new Date(startDate);
    }

    // 获取当前期间数据
    const [
      currentRevenue,
      currentOrders,
      currentUsers,
      currentAdViews,
      prevRevenue,
      prevOrders,
      prevUsers,
      prevAdViews
    ] = await Promise.all([
      // 当前期间收入
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: {
          status: 'completed',
          createdAt: { [Op.between]: [startDate, endDate] }
        },
        raw: true
      }),
      // 当前期间订单数
      Order.count({
        where: {
          createdAt: { [Op.between]: [startDate, endDate] }
        }
      }),
      // 当前期间新用户
      User.count({
        where: {
          role: 'user',
          created_at: { [Op.between]: [startDate, endDate] }
        }
      }),
      // 当前期间广告观看
      AdView.count({
        where: {
          created_at: { [Op.between]: [startDate, endDate] }
        }
      }),
      // 上一期间收入
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: {
          status: 'completed',
          createdAt: { [Op.between]: [prevStartDate, prevEndDate] }
        },
        raw: true
      }),
      // 上一期间订单数
      Order.count({
        where: {
          createdAt: { [Op.between]: [prevStartDate, prevEndDate] }
        }
      }),
      // 上一期间新用户
      User.count({
        where: {
          role: 'user',
          created_at: { [Op.between]: [prevStartDate, prevEndDate] }
        }
      }),
      // 上一期间广告观看
      AdView.count({
        where: {
          created_at: { [Op.between]: [prevStartDate, prevEndDate] }
        }
      })
    ]);

    // 计算变化百分比
    const calculateChange = (current, previous) => {
      if (previous === 0) return current > 0 ? 100 : 0;
      return Math.round(((current - previous) / previous) * 100);
    };

    const totalRevenue = currentRevenue?.total || 0;
    const totalOrders = currentOrders || 0;
    const newUsers = currentUsers || 0;
    const adViews = currentAdViews || 0;

    const prevTotalRevenue = prevRevenue?.total || 0;
    const prevTotalOrders = prevOrders || 0;
    const prevNewUsers = prevUsers || 0;
    const prevTotalAdViews = prevAdViews || 0;

    res.json({
      success: true,
      data: {
        totalRevenue: totalRevenue.toFixed(2),
        totalOrders,
        newUsers,
        adViews,
        revenueChange: calculateChange(totalRevenue, prevTotalRevenue),
        ordersChange: calculateChange(totalOrders, prevTotalOrders),
        usersChange: calculateChange(newUsers, prevNewUsers),
        adViewsChange: calculateChange(adViews, prevTotalAdViews)
      }
    });
  } catch (error) {
    console.error('获取概览数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取概览数据失败',
      error: error.message
    });
  }
});

// 热门产品接口
router.get('/top-products', auth, userAdminAuth, async (req, res) => {
  try {
    const { period = 'week', limit = 10 } = req.query;
    
    // 计算时间范围
    const now = new Date();
    let startDate;
    
    switch (period) {
      case 'day':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        break;
      case 'week':
        const dayOfWeek = now.getDay();
        startDate = new Date(now);
        startDate.setDate(now.getDate() - dayOfWeek);
        startDate.setHours(0, 0, 0, 0);
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      default:
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 7);
    }

    // 获取热门产品数据
    const topProducts = await Order.findAll({
      attributes: [
        [Sequelize.literal('JSON_UNQUOTE(JSON_EXTRACT(items, "$[0].productId"))'), 'productId'],
        [Sequelize.literal('JSON_UNQUOTE(JSON_EXTRACT(items, "$[0].productName"))'), 'productName'],
        [Sequelize.fn('COUNT', Sequelize.col('Order.id')), 'orderCount'],
        [Sequelize.fn('SUM', Sequelize.col('pointsUsed')), 'totalPoints']
      ],
      where: {
        status: 'completed',
        createdAt: { [Op.gte]: startDate }
      },
      group: [
        Sequelize.literal('JSON_UNQUOTE(JSON_EXTRACT(items, "$[0].productId"))'),
        Sequelize.literal('JSON_UNQUOTE(JSON_EXTRACT(items, "$[0].productName"))')
      ],
      order: [[Sequelize.fn('COUNT', Sequelize.col('Order.id')), 'DESC']],
      limit: parseInt(limit),
      raw: true
    });

    res.json({
      success: true,
      data: topProducts.map(product => ({
        id: product.productId,
        name: product.productName,
        orderCount: parseInt(product.orderCount),
        totalPoints: parseFloat(product.totalPoints) || 0
      }))
    });
  } catch (error) {
    console.error('获取热门产品失败:', error);
    res.status(500).json({
      success: false,
      message: '获取热门产品失败',
      error: error.message
    });
  }
});

// 实时数据大屏
router.get('/dashboard/realtime', auth, userAdminAuth, async (req, res) => {
  try {
    const now = new Date();
    const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const yesterday = new Date(today);
    yesterday.setDate(yesterday.getDate() - 1);
    
    const thisMonth = new Date(now.getFullYear(), now.getMonth(), 1);
    const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
    
    // 实时核心指标
    const [
      totalUsers,
      todayNewUsers,
      onlineUsers, // 这里需要实现在线用户统计
      totalOrders,
      todayOrders,
      pendingOrders,
      totalRevenue,
      todayRevenue,
      totalPoints,
      todayPointsIssued
    ] = await Promise.all([
      User.count({ where: { role: 'user' } }),
      User.count({ 
        where: {
          role: 'user',
          created_at: { [Op.gte]: today }
        }
      }),
      User.count({ 
        where: {
          role: 'user',
          last_login: { [Op.gte]: new Date(now - 30 * 60 * 1000) } // 30分钟内活跃
        }
      }),
      Order.count(),
      Order.count({ where: { createdAt: { [Op.gte]: today } } }),
      Order.count({ where: { status: 'pending' } }),
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: { status: 'completed' },
        raw: true
      }).then(result => result?.total || 0),
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: { 
          status: 'completed',
          createdAt: { [Op.gte]: today }
        },
        raw: true
      }).then(result => result?.total || 0),
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('amount')), 'total']],
        raw: true
      }).then(result => result?.total || 0),
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('amount')), 'total']],
        where: { 
          type: 'earn',
          createdAt: { [Op.gte]: today }
        },
        raw: true
      }).then(result => result?.total || 0)
    ]);
    
    res.json({
      success: true,
      data: {
        users: {
          total: totalUsers,
          todayNew: todayNewUsers,
          online: onlineUsers
        },
        orders: {
          total: totalOrders,
          today: todayOrders,
          pending: pendingOrders
        },
        revenue: {
          total: totalRevenue[0]?.total || 0,
          today: todayRevenue[0]?.total || 0
        },
        points: {
          total: totalPoints[0]?.total || 0,
          todayIssued: todayPointsIssued[0]?.total || 0
        },
        timestamp: now
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取实时数据失败',
      error: error.message
    });
  }
});

// 用户行为分析
router.get('/users/behavior', auth, adminAuth, async (req, res) => {
  try {
    const { startDate, endDate, period = 'day' } = req.query;
    
    const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const end = endDate ? new Date(endDate) : new Date();
    
    // 用户增长分析
    const userGrowth = await User.aggregate([
      {
        $match: {
          role: 'user',
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: period === 'day' ? '%Y-%m-%d' : '%Y-%m',
              date: '$createdAt'
            }
          },
          count: { $sum: 1 }
        }
      },
      { $sort: { _id: 1 } }
    ]);
    
    // 用户活跃度分析
    const userActivity = await Order.aggregate([
      {
        $match: {
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: '$userId',
          orderCount: { $sum: 1 },
          totalSpent: { $sum: '$finalAmount' },
          lastOrderDate: { $max: '$createdAt' }
        }
      },
      {
        $group: {
          _id: {
            $cond: [
              { $gte: ['$orderCount', 10] }, 'high',
              { $cond: [
                { $gte: ['$orderCount', 3] }, 'medium', 'low'
              ]}
            ]
          },
          count: { $sum: 1 },
          avgSpent: { $avg: '$totalSpent' }
        }
      }
    ]);
    
    // 用户留存分析
    const retentionData = await calculateRetention(start, end);
    
    res.json({
      success: true,
      data: {
        userGrowth,
        userActivity,
        retention: retentionData
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取用户行为分析失败',
      error: error.message
    });
  }
});

// 业务数据分析
router.get('/business/analysis', auth, adminAuth, async (req, res) => {
  try {
    const { startDate, endDate } = req.query;
    
    const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const end = endDate ? new Date(endDate) : new Date();
    
    // 订单趋势分析
    const orderTrends = await Order.aggregate([
      {
        $match: {
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: {
            date: {
              $dateToString: {
                format: '%Y-%m-%d',
                date: '$createdAt'
              }
            },
            status: '$status'
          },
          count: { $sum: 1 },
          revenue: { $sum: '$finalAmount' }
        }
      },
      { $sort: { '_id.date': 1 } }
    ]);
    
    // 商品销售分析
    const productSales = await Order.aggregate([
      {
        $match: {
          status: 'completed',
          createdAt: { $gte: start, $lte: end }
        }
      },
      { $unwind: '$items' },
      {
        $group: {
          _id: '$items.productId',
          productName: { $first: '$items.productName' },
          totalQuantity: { $sum: '$items.quantity' },
          totalRevenue: { $sum: '$items.totalPrice' },
          orderCount: { $sum: 1 }
        }
      },
      { $sort: { totalRevenue: -1 } },
      { $limit: 20 }
    ]);
    
    // 积分经济分析
    const pointsAnalysis = await PointsTransaction.aggregate([
      {
        $match: {
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: {
            date: {
              $dateToString: {
                format: '%Y-%m-%d',
                date: '$createdAt'
              }
            },
            type: '$type'
          },
          amount: { $sum: '$amount' },
          count: { $sum: 1 }
        }
      },
      { $sort: { '_id.date': 1 } }
    ]);
    
    // 广告效果分析
    const adAnalysis = await Ad.aggregate([
      {
        $group: {
          _id: '$position',
          totalAds: { $sum: 1 },
          totalClicks: { $sum: '$clickCount' },
          totalImpressions: { $sum: '$impressionCount' },
          avgCTR: {
            $avg: {
              $cond: [
                { $gt: ['$impressionCount', 0] },
                { $divide: ['$clickCount', '$impressionCount'] },
                0
              ]
            }
          }
        }
      }
    ]);
    
    res.json({
      success: true,
      data: {
        orderTrends,
        productSales,
        pointsAnalysis,
        adAnalysis
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取业务数据分析失败',
      error: error.message
    });
  }
});

// 财务数据分析
router.get('/finance/analysis', auth, adminAuth, async (req, res) => {
  try {
    const { startDate, endDate, period = 'day' } = req.query;
    
    const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const end = endDate ? new Date(endDate) : new Date();
    
    // 收入趋势分析
    const revenueTrends = await Order.aggregate([
      {
        $match: {
          status: 'completed',
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: {
            $dateToString: {
              format: period === 'day' ? '%Y-%m-%d' : '%Y-%m',
              date: '$createdAt'
            }
          },
          revenue: { $sum: '$finalAmount' },
          orderCount: { $sum: 1 },
          avgOrderValue: { $avg: '$finalAmount' }
        }
      },
      { $sort: { _id: 1 } }
    ]);
    
    // 支付方式分析
    const paymentAnalysis = await Order.aggregate([
      {
        $match: {
          status: 'completed',
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: '$paymentMethod',
          count: { $sum: 1 },
          revenue: { $sum: '$finalAmount' }
        }
      }
    ]);
    
    // 积分成本分析
    const pointsCost = await PointsTransaction.aggregate([
      {
        $match: {
          type: 'earn',
          createdAt: { $gte: start, $lte: end }
        }
      },
      {
        $group: {
          _id: '$source',
          totalPoints: { $sum: '$amount' },
          count: { $sum: 1 },
          estimatedCost: { $sum: { $multiply: ['$amount', 0.01] } } // 1积分=0.01元成本
        }
      }
    ]);
    
    res.json({
      success: true,
      data: {
        revenueTrends,
        paymentAnalysis,
        pointsCost
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取财务数据分析失败',
      error: error.message
    });
  }
});

// 报表生成和导出
router.get('/reports/generate', auth, adminAuth, async (req, res) => {
  try {
    const { type, startDate, endDate, format = 'json' } = req.query;
    
    const start = startDate ? new Date(startDate) : new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
    const end = endDate ? new Date(endDate) : new Date();
    
    let reportData = {};
    
    switch (type) {
      case 'user':
        reportData = await generateUserReport(start, end);
        break;
      case 'order':
        reportData = await generateOrderReport(start, end);
        break;
      case 'revenue':
        reportData = await generateRevenueReport(start, end);
        break;
      case 'points':
        reportData = await generatePointsReport(start, end);
        break;
      default:
        reportData = await generateComprehensiveReport(start, end);
    }
    
    if (format === 'csv') {
      // 这里可以实现CSV导出逻辑
      res.setHeader('Content-Type', 'text/csv');
      res.setHeader('Content-Disposition', `attachment; filename="${type}_report_${Date.now()}.csv"`);
      // 实现CSV转换逻辑
    }
    
    res.json({
      success: true,
      data: reportData,
      meta: {
        type,
        startDate: start,
        endDate: end,
        generatedAt: new Date()
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '生成报表失败',
      error: error.message
    });
  }
});

// 辅助函数：计算用户留存
async function calculateRetention(startDate, endDate) {
  // 实现用户留存计算逻辑
  const cohorts = await User.aggregate([
    {
      $match: {
        role: 'user',
        createdAt: { $gte: startDate, $lte: endDate }
      }
    },
    {
      $group: {
        _id: {
          $dateToString: {
            format: '%Y-%m-%d',
            date: '$createdAt'
          }
        },
        users: { $push: '$_id' }
      }
    }
  ]);
  
  // 这里需要实现更复杂的留存计算逻辑
  return cohorts;
}

// 辅助函数：生成综合报表
async function generateComprehensiveReport(startDate, endDate) {
  const [userStats, orderStats, revenueStats, pointsStats] = await Promise.all([
    generateUserReport(startDate, endDate),
    generateOrderReport(startDate, endDate),
    generateRevenueReport(startDate, endDate),
    generatePointsReport(startDate, endDate)
  ]);
  
  return {
    users: userStats,
    orders: orderStats,
    revenue: revenueStats,
    points: pointsStats
  };
}

// 辅助函数：生成用户报表
async function generateUserReport(startDate, endDate) {
  return await User.aggregate([
    {
      $match: {
        role: 'user',
        createdAt: { $gte: startDate, $lte: endDate }
      }
    },
    {
      $group: {
        _id: {
          $dateToString: {
            format: '%Y-%m-%d',
            date: '$createdAt'
          }
        },
        newUsers: { $sum: 1 }
      }
    },
    { $sort: { _id: 1 } }
  ]);
}

// 辅助函数：生成订单报表
async function generateOrderReport(startDate, endDate) {
  return await Order.aggregate([
    {
      $match: {
        createdAt: { $gte: startDate, $lte: endDate }
      }
    },
    {
      $group: {
        _id: {
          date: {
            $dateToString: {
              format: '%Y-%m-%d',
              date: '$createdAt'
            }
          },
          status: '$status'
        },
        count: { $sum: 1 },
        totalAmount: { $sum: '$finalAmount' }
      }
    },
    { $sort: { '_id.date': 1 } }
  ]);
}

// 辅助函数：生成收入报表
async function generateRevenueReport(startDate, endDate) {
  return await Order.aggregate([
    {
      $match: {
        status: 'completed',
        createdAt: { $gte: startDate, $lte: endDate }
      }
    },
    {
      $group: {
        _id: {
          $dateToString: {
            format: '%Y-%m-%d',
            date: '$createdAt'
          }
        },
        revenue: { $sum: '$finalAmount' },
        orderCount: { $sum: 1 },
        avgOrderValue: { $avg: '$finalAmount' }
      }
    },
    { $sort: { _id: 1 } }
  ]);
}

// 用户分析接口
router.get('/user-analysis', auth, userAdminAuth, async (req, res) => {
  try {
    const { period = 'week' } = req.query;
    
    // 计算时间范围
    const now = new Date();
    let startDate;
    
    switch (period) {
      case 'today':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        break;
      case 'week':
        const dayOfWeek = now.getDay();
        startDate = new Date(now);
        startDate.setDate(now.getDate() - dayOfWeek);
        startDate.setHours(0, 0, 0, 0);
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1);
        break;
      default:
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 7);
    }

    // 获取用户分析数据
    const [totalUsers, activeUsers, totalOrders, totalRevenue] = await Promise.all([
      User.count({ where: { role: 'user' } }),
      User.count({ 
        where: {
          role: 'user',
          last_login: { [Op.gte]: startDate }
        }
      }),
      Order.count({ where: { createdAt: { [Op.gte]: startDate } } }),
      Order.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('finalAmount')), 'total']],
        where: {
          status: 'completed',
          createdAt: { [Op.gte]: startDate }
        },
        raw: true
      })
    ]);

    const activeRate = totalUsers > 0 ? Math.round((activeUsers / totalUsers) * 100) : 0;
    const avgOrderAmount = totalOrders > 0 ? ((totalRevenue?.total || 0) / totalOrders).toFixed(2) : '0';
    
    // 简化的留存率和积分使用率计算
    const retentionRate = Math.round(Math.random() * 30 + 60); // 临时数据
    const pointsUsageRate = Math.round(Math.random() * 20 + 70); // 临时数据

    res.json({
      success: true,
      data: {
        activeRate,
        avgOrderAmount,
        retentionRate,
        pointsUsageRate
      }
    });
  } catch (error) {
    console.error('获取用户分析失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户分析失败',
      error: error.message
    });
  }
});

// 趋势数据接口
router.get('/trends', auth, userAdminAuth, async (req, res) => {
  try {
    const { period = 'week' } = req.query;
    
    // 计算时间范围和数据点
    const now = new Date();
    let startDate, dataPoints = [];
    
    switch (period) {
      case 'today':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        // 生成24小时的数据点
        for (let i = 0; i < 24; i++) {
          const hour = new Date(startDate);
          hour.setHours(i);
          dataPoints.push({
            date: `${i}:00`,
            value: Math.round(Math.random() * 1000 + 500)
          });
        }
        break;
      case 'week':
        const dayOfWeek = now.getDay();
        startDate = new Date(now);
        startDate.setDate(now.getDate() - dayOfWeek);
        startDate.setHours(0, 0, 0, 0);
        // 生成7天的数据点
        const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        for (let i = 0; i < 7; i++) {
          dataPoints.push({
            date: weekDays[i],
            value: Math.round(Math.random() * 2000 + 1000)
          });
        }
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        // 生成30天的数据点
        for (let i = 1; i <= 30; i++) {
          dataPoints.push({
            date: `${i}日`,
            value: Math.round(Math.random() * 3000 + 1500)
          });
        }
        break;
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1);
        // 生成12个月的数据点
        const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
        for (let i = 0; i < 12; i++) {
          dataPoints.push({
            date: months[i],
            value: Math.round(Math.random() * 10000 + 5000)
          });
        }
        break;
    }

    res.json({
      success: true,
      data: dataPoints
    });
  } catch (error) {
    console.error('获取趋势数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取趋势数据失败',
      error: error.message
    });
  }
});

// 广告数据接口
router.get('/ads', auth, userAdminAuth, async (req, res) => {
  try {
    const { period = 'week' } = req.query;
    
    // 计算时间范围
    const now = new Date();
    let startDate;
    
    switch (period) {
      case 'today':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        break;
      case 'week':
        const dayOfWeek = now.getDay();
        startDate = new Date(now);
        startDate.setDate(now.getDate() - dayOfWeek);
        startDate.setHours(0, 0, 0, 0);
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1);
        break;
      default:
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 7);
    }

    // 获取广告数据
    const totalViews = await AdView.count({
      where: {
        created_at: { [Op.gte]: startDate }
      }
    });

    const totalEarned = await AdView.findOne({
      attributes: [[Sequelize.fn('SUM', Sequelize.col('points_earned')), 'total']],
      where: {
        created_at: { [Op.gte]: startDate }
      },
      raw: true
    });

    // 模拟完成率和收益数据
    const completionRate = totalViews > 0 ? Math.round(Math.random() * 20 + 75) : 0;
    const revenue = ((totalEarned?.total || 0) * 0.01).toFixed(2); // 1积分=0.01元

    res.json({
      success: true,
      data: {
        totalViews,
        completionRate,
        revenue: parseFloat(revenue)
      }
    });
  } catch (error) {
    console.error('获取广告数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取广告数据失败',
      error: error.message
    });
  }
});

// 积分数据接口
router.get('/points', auth, userAdminAuth, async (req, res) => {
  try {
    const { period = 'week' } = req.query;
    
    // 计算时间范围
    const now = new Date();
    let startDate;
    
    switch (period) {
      case 'today':
        startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        break;
      case 'week':
        const dayOfWeek = now.getDay();
        startDate = new Date(now);
        startDate.setDate(now.getDate() - dayOfWeek);
        startDate.setHours(0, 0, 0, 0);
        break;
      case 'month':
        startDate = new Date(now.getFullYear(), now.getMonth(), 1);
        break;
      case 'year':
        startDate = new Date(now.getFullYear(), 0, 1);
        break;
      default:
        startDate = new Date(now);
        startDate.setDate(now.getDate() - 7);
    }

    // 获取积分数据
    const [earnedPoints, spentPoints] = await Promise.all([
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('amount')), 'total']],
        where: {
          type: 'earn',
          createdAt: { [Op.gte]: startDate }
        },
        raw: true
      }),
      PointsTransaction.findOne({
        attributes: [[Sequelize.fn('SUM', Sequelize.col('amount')), 'total']],
        where: {
          type: 'spend',
          createdAt: { [Op.gte]: startDate }
        },
        raw: true
      })
    ]);

    const totalEarned = earnedPoints?.total || 0;
    const totalSpent = Math.abs(spentPoints?.total || 0);
    const usageRate = totalEarned > 0 ? Math.round((totalSpent / totalEarned) * 100) : 0;

    res.json({
      success: true,
      data: {
        totalEarned,
        totalSpent,
        usageRate
      }
    });
  } catch (error) {
    console.error('获取积分数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取积分数据失败',
      error: error.message
    });
  }
});

// 辅助函数：生成积分报表
async function generatePointsReport(startDate, endDate) {
  return await PointsTransaction.aggregate([
    {
      $match: {
        createdAt: { $gte: startDate, $lte: endDate }
      }
    },
    {
      $group: {
        _id: {
          date: {
            $dateToString: {
              format: '%Y-%m-%d',
              date: '$createdAt'
            }
          },
          type: '$type'
        },
        amount: { $sum: '$amount' },
        count: { $sum: 1 }
      }
    },
    { $sort: { '_id.date': 1 } }
  ]);
}

module.exports = router;